package com.jy.modules.cims.settle.controller;

import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.buyback.service.BuyBackConfirmService;
import com.jy.modules.cims.buyback.service.BuyBackDeleteService;
import com.jy.modules.cims.buyback.service.BuyBackQueryService;
import com.jy.modules.cims.buyback.service.BuyBackSaveService;
import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsException;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.component.common.service.TCMmCooperorgDealService;
import com.jy.modules.cims.contract.service.ContractService;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmQuotaDTO;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.CreditRightDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.RedemptionCreditDetailDto;
import com.jy.modules.cims.data.dto.loan.LoanRedemptionDto;
import com.jy.modules.cims.data.dto.loan.LoanTransferCrossBillDateDto;
import com.jy.modules.cims.deal.service.DealService;
import com.jy.modules.cims.deal.service.LoanDealService;
import com.jy.modules.cims.loan.service.LoanBuybackSettleService;
import com.jy.modules.cims.settle.service.CreditRedemptionService;
import com.jy.platform.api.org.SessionAPI;
import com.jy.platform.api.org.UserInfo;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
import com.jy.platform.restservice.web.base.BaseController;

/**
 * 结算处理控制层
 */
@Controller
@RequestMapping("/loanRedem")
public class LoanRedemptionController extends BaseController{
	private static final String JSP_URL="cims/loanDealManage/";
    /**
     * 结算处理控制层[
     */
    public LoanRedemptionController() {
    }
    @Autowired
    @Qualifier("com.jy.modules.cims.deal.service.DealService")
    public DealService dealService;
    @Autowired
    @Qualifier("com.jy.modules.cims.settle.service.CreditRedemptionService")
    public CreditRedemptionService creditRedemptionService;
    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmCooperorgDealService")
    private TCMmCooperorgDealService cooperorgDealService;
    @Autowired
    @Qualifier("com.jy.modules.cims.contract.service.ContractService")
    private ContractService serviceContract;
    @Autowired
    @Qualifier("com.jy.modules.cims.deal.service.LoanDealService")
    private LoanDealService loanDealService;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.loan.service.LoanBuybackSettleService")
    private LoanBuybackSettleService loanBuybackSettleService;
    
    
    @Autowired
    @Qualifier("com.jy.modules.cims.buyback.service.BuyBackDeleteService")
    public BuyBackDeleteService buyBackDeleteService;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.buyback.service.BuyBackSaveService")
    public BuyBackSaveService buyBackSaveService;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.buyback.service.BuyBackQueryService")
    public BuyBackQueryService buyBackQueryService;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.buyback.service.BuyBackConfirmService")
    public BuyBackConfirmService buyBackConfirmService;
    
    @Autowired
    public SessionAPI sessionAPI;
    
    /**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        if("toQueryPage".equals(operate)){//跳转至 查询页面
        	model.setViewName(JSP_URL+"queryCreditRedem");
        }else if("toAdd".equals(operate)){ //跳转至 新增页面
    		model.setViewName(JSP_URL+"addCreditRedem");
        }else if("toBackRedemptionAdd".equals(operate)){//跳转至贷款交易新增页面
        	String contractCode = this.getParameterString("contractCode");
        	model = serviceContract.queryAllDTO(contractCode);
        	model.setViewName(JSP_URL+"addCreditRedem");
        }else if("toBackRedemptionUpdate".equals(operate)){//跳转至债权交易修改页面
        	String contractCode = this.getParameterString("contractCode");
        	String dealCode = this.getParameterString("dealCode");
        	String cooperorgCode = this.getParameterString("cooperorgCode");
        	String cooperativeAgencyDealStatus = this.getParameterString("cooperativeAgencyDealStatus");
        	String id = this.getParameterString("id");
        	model = serviceContract.queryAllDTO(cooperorgCode,contractCode,dealCode);
        	model.addObject("id", id);
        	model.addObject("dealCode", dealCode);
        	model.addObject("cooperativeAgencyDealStatus", cooperativeAgencyDealStatus);
        	model.setViewName(JSP_URL+"updateRedemption");
        } else if ("intoMatchCredit".equals(operate)) {
        	//进入查看贷款回购匹配债权信息
         	model.setViewName("cims/loanDealManage/queryMatchCredit");
//        	model.setViewName("cims/paramManage/selectTCMmContract");
        	
        }
        
        return model;
    }

    /**
     * 结算处理
     * @param request 
     * @param response 
     * @return
     */
    public DataMsg settle(HttpServletRequest request, HttpServletResponse response) {
        return null;
    }

    /**
     * 试算处理
     * @param request 
     * @param response 
     * @param result
     */
    public void trial(HttpServletRequest request, HttpServletResponse response, DataMsg result) {
    }
    
    
    /**
     * @author JY-IT-D001
     * @description:通过主键查询 其明细信息
     * @date 2015-01-14 10:07:19
     * @param id
     * @return
     */
    private ModelAndView queryOneDTO(String id) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	TCMmQuotaDTO dto=new TCMmQuotaDTO();
//        	TCMmQuotaDTO dto = service.queryTCMmQuotaByPrimaryKey(id);
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
        return model;
    }
    
    
    /**
     * 
     * @Title save
     * @Description 保存交易
     * @param request
     * @param response
     * @param result 
     * void 
     * @author lizhiqiang
     * @date 2015-1-20-上午9:45:29
     * @update 
     * @throws
     */
    @RequestMapping(value = "/testSettleCooperorgDeal")
    @ResponseBody
    public DataMsg testSettleCooperorgDeal(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
    	 try {
         	 dto = (DealDto)super.initDto(dto);
//         	dealService.updateCreditDealDetailToCreditDetail(dto);
         	
             dataMsg = super.initDataMsg(dataMsg);
             dataMsg.setMsg("试算完成！");
             dataMsg.setData(this.makeJSONData(dto.getId()));
         }catch (Exception e) {
         	dataMsg.failed(e.getMessage());
         	logger.error("执行方法insertSysResource异常：", e);
         }
         return dataMsg;
    }
    
	/**
	 * 债权赎回交易流水查询
	 * @Title getDealCreditList
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return 
	 * DataMsg 
	 * @author lizhiqiang
	 * @date 2015-3-2-下午7:59:38
	 * @update 
	 * @throws
	 */
    @RequestMapping(value = "/getDealCreditRedemptionList")
    @ResponseBody
    public DataMsg getDealCreditRedemptionList(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	dto.setDealType(CimsConstant.DEAL_TYPE_CREDIT_REDEEM);
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
        List<DealDto> list = dealService.getDealList(params.getSearchParams());
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
	
    /**
     * @throws ParseException 
     * 新建回购，选择回购日期后触发查询
     * @Title getCreditDetailRedemptionList
     * @param request
     * @param dto
     * @param dataMsg
     * @return 
     * DataMsg 
     * @author yujiazheng
     * @date 2015-12-14-上午11:42:40
     * @update 
     * @throws
     */
    @RequestMapping(value = "/getCreditDetailRedemptionList")
    @ResponseBody
    public DataMsg getCreditDetailRedemptionList(HttpServletRequest request, TCMmCreditDetailDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
//    	String cooperorgCode = this.getParameterString("valueCooperorgCode");// 合作机构编号
    	String contractCode = this.getParameterString("valueContractCode");// 合约编号
    	String packageNum = this.getParameterString("creditPackage");// 债权包编号
    	String redeemDate = this.getParameterString("redemptionDate");// 回购日期
        QueryReqBean params = new QueryReqBean();
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		Map<String, Object> paramMap = buyBackQueryService.getBuyBackParamMap(contractCode, packageNum, redeemDate);
        params.setSearchParams(paramMap);
        params.setPageParameter(pageInfo);
        List<TCMmCreditDetailDTO> list = buyBackQueryService.getBuyBackDetailList(params.getSearchParams(), redeemDate);
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    
    /**
     * 修改回购，查询明细
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getCreditDetailByBatchId")
    @ResponseBody
    public DataMsg getCreditDetailByBatchId(HttpServletRequest request, TCMmCreditDetailDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
    	String batchId = this.getParameterString("batchId");// 批次号
        QueryReqBean params = new QueryReqBean();
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("batchId", batchId);
        params.setSearchParams(paramMap);
        params.setPageParameter(pageInfo);
        List<CreditDetailDto> list = buyBackQueryService.getBuyBackDetailListByBatchId(params.getSearchParams());
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    
    
    /**
     * 选择赎回的债权
     */
    @RequestMapping(value = "/updateCreditForRedemption")
    @ResponseBody
    public DataMsg updateCreditForRedemption(HttpServletRequest request, RedemptionCreditDetailDto dto, @ModelAttribute DataMsg dataMsg) throws Exception{
    	try {
	    	dto = (RedemptionCreditDetailDto)super.initDto(dto);
	    	String dealCode = dto.getDealCode();
	    	Long dealId = null ;
	    	if(StringUtil.isBlank(dto.getDealCode())){
		    	// 创建交易流水信息
		    	DealDto dealDto = new DealDto();
	         	StringBuffer dealCodesb = new StringBuffer();
	         	creditRedemptionService.doGetDealCode(dealCodesb);
	         	dealCode = dealCodesb.toString();
	         	dealDto.setDealCode(dealCode);//交易流水号
	         	dealDto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_CREATE);//新建
	         	dealDto.setDealType(CimsConstant.DEAL_TYPE_CREDIT_REDEEM);
	         	dealId = cooperorgDealService.insertTCMmCooperorgDeal(dealDto);
	    	}
         	Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("id", dealId);
            resultMap.put("dealCode", dealCode);
         	//保存挑选结果
	    	TCMmCooperorgDealDTO dealdto = new TCMmCooperorgDealDTO();
	    	dealdto.setDealCode(dealCode);
	    	creditRedemptionService.saveCreditDealDetail(dto, dealdto);
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("修改成功");
            dataMsg.setData(resultMap);
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
            logger.error("执行方法updateSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @Title save
     * @Description 保存赎回交易
     * @param request
     * @param response
     * @param result  
     * @author yujiazheng
     * @date 2015-12-20-上午9:45:29
     * @update 
     * @throws
     */
    @RequestMapping(value = "/saveRedemptionDeal")
    @ResponseBody
    public DataMsg saveRedemptionDeal(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
		dto = (DealDto)super.initDto(dto);
		String cooperorgCode = dto.getCooperorgCode();// 合作机构编号
    	String contractCode = dto.getContractCode();// 合约编号
    	String packageNum = this.getParameterString("creditPackage");// 债权包编号
    	String redemptionDate  = this.getParameterString("redemptionDate");// 回购日期
    	String agreementCode = dto.getAgreementCode();// 协议编号
    	String deleteContractNos = this.getParameterString("deleteContractNos");// 删除的合同号
    	String[] deleteContractNoArr = null;
    	if (deleteContractNos != null && !"".equals(deleteContractNos)) {
    		deleteContractNoArr = deleteContractNos.split(",");
    	}
    	 String dealCode = "";
    	 String msg = "";
    	 String status = "";
 		UserInfo userInfo = sessionAPI.getCurrentUserInfo();
 		String userId = String.valueOf(userInfo.getUserId());

		try {
			dealCode = buyBackSaveService.insertLoanCreditDetail(redemptionDate, cooperorgCode, 
										agreementCode, contractCode, packageNum, userId, deleteContractNoArr);
			msg = "贷款回购新增成功！";
			status = DataMsg.STATUS_OK;
		} catch (Exception e) {
			msg = e.getMessage();
			status = DataMsg.STATUS_FAILED;
			logger.error(e.getMessage(), e);
		}
		 Map<String, Object> resultMap = new HashMap<String, Object>();
		 resultMap.put("dealCode", dealCode);
		 dataMsg = super.initDataMsg(dataMsg);
		 dataMsg.setMsg(msg);
		 dataMsg.setData(resultMap); 
		 dataMsg.setStatus(status);
		 
		 return dataMsg;
    }
	/**
	 * 删除赎回交易明细信息
	 * 
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/deleteDetailByCredit")
	@ResponseBody
	public DataMsg deleteDetailByCredit(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		BaseDTO dto = super.initDto(null);
		String transferIds = (String) this.getParameter("transferIds");// 格式:
		String dealCode = (String) this.getParameter("dealCode");
		dataMsg = super.initDataMsg(dataMsg);
		try {
			dealService.removeDetailByCredit(dto, transferIds,dealCode);
			dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSysResource异常：", e);
		}

		return dataMsg;
	}
	
	/**
	 * 删除赎回交易
	 * 
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/deleteDeal")
	@ResponseBody
	public DataMsg deleteDeal(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		String ids = (String) this.getParameter("ids");// 格式: 1,2,3
		dataMsg = super.initDataMsg(dataMsg);
		String resultstr = null;
		try {
	     resultstr = loanDealService.doDeleteDeal(ids);
			dataMsg.setMsg(resultstr);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSysResource异常：", e);
		}
		return dataMsg;
	}
	
	/**
	 * 按照明细删除赎回交易
	 * 
	 * @param request
	 * @param response
	 * @param result
	 * @author zhoupeng
	 * @date 2016-07-06
	 */
	@RequestMapping(value = "/releaseData")
	@ResponseBody
	public DataMsg releaseData(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		String transferId = (String) this.getParameter("creditCode");// 合同号
		String creditorStatus = (String) this.getParameter("creditorStatus");//  债权状态
		String dealCode = (String) this.getParameter("dealCode");//  流水号
		dataMsg = super.initDataMsg(dataMsg);
		try {
			buyBackDeleteService.doDeleteDetail(transferId,creditorStatus,dealCode);
			dataMsg.setMsg("合同号:" + transferId + "删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return dataMsg;
	}
	
	/**
	 * @Description 完成贷款赎回
	 * @param request
	 * @param dataMsg
	 * @return   
	 * DataMsg  
	 * @throws
	 * @author yanjingying
	 * @date 2015-12-26
	 */
	@RequestMapping(value = "/saveLoanTransferRedeem")
	@ResponseBody
	public DataMsg saveLoanTransferRedeem(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		super.initDto(null);
		String dealCode = (String) this.getParameter("dealCode");// 格式: 1,2,3
		dataMsg = super.initDataMsg(dataMsg);
		try {
			Map<String, Object> searchParams = new HashMap<String, Object>();
			TCMmCooperorgDealDTO cooperorgDealDTO = new TCMmCooperorgDealDTO();
			cooperorgDealDTO.setDealCode(dealCode);
         	searchParams.put("dto", cooperorgDealDTO);
         	cooperorgDealDTO = cooperorgDealService.searchTCMmCooperorgDeal(searchParams).get(0);
         	Map<String, String> retMap = buyBackConfirmService.doBuyBackConfirm(cooperorgDealDTO, dealCode);   //调用贷款回购交易并返回弹出信息
         	String totalRes = retMap.get("totalRes");
         	String totalMsg = retMap.get("totalMsg");
         	if ("true".equals(totalRes)) {
         		dataMsg.setStatus(DataMsg.STATUS_OK);
         	} else {
         		dataMsg.setStatus(DataMsg.STATUS_FAILED);
         	}
         	dataMsg.setMsg(totalMsg);
		} catch (ConnectException e){
			String returnMsg = "连接核心接口网络失败，请检查网络!";
			dataMsg.failed(returnMsg);
			logger.error("执行方法saveLoanTransferRedeem异常：", e);
		}catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法saveLoanTransferRedeem异常：", e);
		} 
		return dataMsg;
	}
	
	/**
	 * @Description 获取贷款回购跨账单日的结果列表
	 * @param request
	 * @param dataMsg
	 * @return   
	 * DataMsg  
	 * @throws
	 * @author yanjingying
	 * @date 2015-12-29
	 * */
	@RequestMapping(value = "/getLoanTransferCrossBillDate")
	@ResponseBody
	public DataMsg getLoanTransferCrossBillDate(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
		super.initDto(null);
		String dealCode = (String) this.getParameter("dealCode");// 格式: 1,2,3
		dataMsg = super.initDataMsg(dataMsg);
		try {
			Map<String, Object> searchParams = new HashMap<String, Object>();
			TCMmCooperorgDealDTO cooperorgDealDTO = new TCMmCooperorgDealDTO();
			cooperorgDealDTO.setDealCode(dealCode);
         	searchParams.put("dto", cooperorgDealDTO);
         	cooperorgDealDTO = cooperorgDealService.searchTCMmCooperorgDeal(searchParams).get(0);
         	List<LoanTransferCrossBillDateDto> loanTransferCrossBillDateDtoList = dealService.doLoanTransferCrossBillDate(cooperorgDealDTO);
         	if(loanTransferCrossBillDateDtoList != null && loanTransferCrossBillDateDtoList.size() > 0){
         		String returnMsg = "验证失败，";
         		int i = 1;
         		for(LoanTransferCrossBillDateDto dto:loanTransferCrossBillDateDtoList){
             		i++;
         			/*returnMsg += "\r\n跨账单日信息" + i++ +":"
             				+ "  合同编号："+ dto.getCreditorId() 
             				+ "  债权编号:"+ dto.getTransferId() 
             				+ "  账单日："+ dto.getBillDate() 
             				+ "  赎回日期："+ DateTimeUtils.formatDate(dto.getRedeemDate(), DateTimeUtils.DEFAULT_DATE_TIME_FORMAT).substring(0, 10)
             				+ "  赎回确认日期："+ DateTimeUtils.formatDate(dto.getRedeemConfirmDate(), DateTimeUtils.DEFAULT_DATE_TIME_FORMAT).substring(0, 10) 
             				+ "  下一账单日:" + DateTimeUtils.formatDate(dto.getNextBillDate(), DateTimeUtils.DEFAULT_DATE_TIME_FORMAT).substring(0, 10) ;*/
             	}
         		returnMsg += "共计有"+ (i-1) +"条信息跨账单日！";
         		dataMsg.setMsg(returnMsg);
         		dataMsg.setStatus(DataMsg.STATUS_FAILED);
         	}else{
         		String returnMsg = "验证成功，无跨账单日信息！";
         		dataMsg.setMsg(returnMsg);
         		dataMsg.setStatus(DataMsg.STATUS_OK);
         	}
		}catch(Exception e){
			dataMsg.failed(e.getMessage());
			logger.error("执行方法getLoanTransferCrossBillDate异常：", e);
			throw new CimsException(e.getMessage());
		}
		return dataMsg;
	}
	
	/**
	 * @Description 验证贷款回购业务合法性
	 * @param request
	 * @param dataMsg
	 * @return   
	 * DataMsg  
	 * @throws
	 * @author yanjingying
	 * @date 2015-12-29
	 * */
	@RequestMapping(value = "/getLoanTransferBusinessValid")
	@ResponseBody
	public DataMsg getLoanTransferBusinessValid(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
		super.initDto(null);
		String dealCode = (String) this.getParameter("dealCode");// 格式: 1,2,3
		dataMsg = super.initDataMsg(dataMsg);
		String returnMsg = "";   //返回信息
		try {
			Map<String, Object> searchParams = new HashMap<String, Object>();
			TCMmCooperorgDealDTO cooperorgDealDTO = new TCMmCooperorgDealDTO();
			cooperorgDealDTO.setDealCode(dealCode);
         	searchParams.put("dto", cooperorgDealDTO);
         	cooperorgDealDTO = cooperorgDealService.searchTCMmCooperorgDeal(searchParams).get(0);
         	Date redeemDate = cooperorgDealDTO.getRedemptionDate();  //回购日期
         	Date confirmDate = new Date();                           //确认日期
         	
         	//将回购日期、确认日期，统一进行格式处理年月日时分秒，处理后的时分秒统一变成00:00:00
         	redeemDate = DateTimeUtils.parseDate(DateTimeUtils.getCurrentDateYMDHMS(redeemDate), DateTimeUtils.DEFAULT_DATE_TIME_FORMAT);
         	confirmDate = DateTimeUtils.parseDate(DateTimeUtils.getCurrentDateYMDHMS(confirmDate), DateTimeUtils.DEFAULT_DATE_TIME_FORMAT);
         	
         	//验证回购日期、确认日期，保证确认日期必须大于等于回购日期
         	if(DateTimeUtils.diffDays(confirmDate, redeemDate)>=0){
         		returnMsg = "验证成功！";
         		dataMsg.setStatus(DataMsg.STATUS_OK);
         	}else{
         		returnMsg = "业务合法性校验不通过，请务必保证【确认日期】必须大于等于【回购日期】！" 
         					+ "确认日期：" + DateTimeUtils.getCurrentDateYMDHMS(confirmDate).substring(0,10) 
         					+ "，回购日期："+ DateTimeUtils.getCurrentDateYMDHMS(redeemDate).substring(0,10) + "！";
         		dataMsg.setStatus(DataMsg.STATUS_FAILED);
         	}
         	dataMsg.setMsg(returnMsg);
		}catch(Exception e){
			dataMsg.failed(e.getMessage());
			logger.error("执行方法getLoanTransferBusinessValid异常：", e);
		}
		return dataMsg;
	}
	
	/**
	 * 根据交易流水查询贷款回购交易汇总信息
	 * T_C_MM_COOPERORG_DEAL T_C_MM_COOPERORG T_C_MM_AGREEMENT T_C_MM_CONTRACT 
	 * @Title getDealLoanCreditRedemptionList
	 * @Description TODO
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return 
	 * @author yujiazheng
	 * @date 2015-12-15-下午10:59:38
	 * @update 
	 * @throws
	 */
	@RequestMapping(value = "/getDealLoanCreditRedemptionList")
    @ResponseBody
    public DataMsg getDealLoanCreditRedemptionList(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	dto.setDealType(CimsConstant.DEAL_TYPE_LOAN_CREDIT_REDEEM);// 14-贷款赎回
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
        List<DealDto> list = dealService.getDealList(params.getSearchParams());
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
	
	/**
	 * 贷款回购导入CALLBACK功能实现
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 * @author yujiazheng
	 * @date 2015-12-15-下午10:59:38
	 * @throws Exception
	 */
	@RequestMapping(value = "/doTransfereeDeal")
	@ResponseBody
	public DataMsg doTransfereeDeal(HttpServletRequest request,LoanRedemptionDto dto, @ModelAttribute DataMsg dataMsg) throws Exception{
		
	   logger.info("--------------导入 进行中------------------------------------"+dto.getDataType());
	   String dataType = dto.getDataType() == null ? "" : dto.getDataType().trim();
		List<CreditDetailDto> creditDetailList = new ArrayList<CreditDetailDto>();
		if (CimsConstant.SESSION_IMPORT_DATA_PATH.equals(dataType)) {// 01-session 存储方式，本次改造默认为session储存
			creditDetailList = (List<CreditDetailDto>) request.getSession().getAttribute(dto.getDataId());
		} 
		//UserInfo userInfo = sessionAPI.getCurrentUserInfo();
		//String userId = String.valueOf(userInfo.getUserId());
		try{
			// 解析后的excel数据 组装入库
			dto.setCreditDetailList(creditDetailList);
			loanDealService.updateTCMmCreditDealDetail(dto);
				
			dataMsg.setData(dto);
			dataMsg.setStatus("ok");
			dataMsg.setMsg("调用creditDealService.doTransferee成功！");
		} catch (Exception e) {
			dataMsg.setStatus("error");
			dataMsg.setMsg(e.getMessage());
			request.getSession().removeAttribute(dto.getDataId());//从session中移除数据
			logger.error("执行方法creditDealService.doTransferee异常：", e);
		}
		return dataMsg;
	}
	
	/**
	 * 回购价格合计、本次回购债权价值合计、本次回购债权条数合计方法入口
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @author yujiazheng
	 * @date 2015-12-15-下午10:59:38
	 * @return
	 */
	@RequestMapping(value = "/getDealDetailByCreditSumTotal")
	@ResponseBody
	public DataMsg getDealDetailByCreditSumTotal(HttpServletRequest request, DealDto dto,@ModelAttribute DataMsg dataMsg){
		String dealCode = dto.getDealCode();// 交易流水号
		CreditRightDto creditRightDto =  loanDealService.getDealDetailByCreditSumTotal(dealCode);
		dataMsg.setData(creditRightDto);
		return dataMsg;
	}
	
	/**
	 * 发送结算申请
	 * @Title settleDeal
	 * @Description TODO
	 * @param request
	 * @param dataMsg
	 * @return 
	 * DataMsg 
	 * @author yanjingying
	 * @date 2016-08-19-上午10:14:37
	 * @update 
	 * @throws
	 */
	@RequestMapping(value = "/settleDeal")
	@ResponseBody
	public DataMsg settleDeal(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
   	 	String ids =(String) this.getParameter("ids");  //交易流水号字符串
   	 	String resultstr = null;
	   	try {
	   		resultstr = loanBuybackSettleService.doLoanBuybackSettleMore(ids);
			dataMsg.setMsg(resultstr);
			dataMsg.setStatus("ok");
		} catch (Exception e) {
			dataMsg.setMsg("贷款回购结算申请失败！");
			dataMsg.setStatus("error");
			dataMsg.failed(e.getMessage());
			logger.error("执行方法doLoanBuybackSettleMore异常：", e);
		}
        return dataMsg;
	}
	
	
	 /**
     * 查看贷款回购匹配债权信息
     */
	@RequestMapping(value = "/getMatchCreditList")
	@ResponseBody
	public DataMsg getMatchCreditList(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		String batchId = this.getParameterString("batchId");
		String transferId = this.getParameterString("transferId");
		
	   	try {
			Map<String, Object> searchParams = new HashMap<String, Object>();
			searchParams.put("batchId", batchId);
			searchParams.put("transferId", transferId);
	   		QueryReqBean params = new QueryReqBean();
	        params.setSearchParams(searchParams);
	    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
			params.setPageParameter(pageInfo);
	        List<CreditDetailDto> list = buyBackQueryService.getMatchCreditList(params.getSearchParams());
	        dataMsg.setData(list);
	        dataMsg.setTotalRows(pageInfo.getTotalCount());
			dataMsg.setStatus("ok");
		} catch (Exception e) {
			dataMsg.setMsg("查看贷款回购匹配债权信息查询失败！");
			dataMsg.setStatus("fail");
			dataMsg.failed(e.getMessage());
			logger.error(e.getMessage(), e);
		}
        return dataMsg;
	}
	
	
	/**
	 * 
	 * @Title finishDeal
	 * @Description TODO
	 * @return 
	 * DateMsg 
	 * @author lizhiqiang
	 * @date 2016-12-27-下午3:09:22
	 * @update 
	 * @throws
	 */
	@RequestMapping(value = "/finishDeal")
	@ResponseBody
	public DataMsg finishDeal(HttpServletRequest request,DealDto dto,  @ModelAttribute DataMsg dataMsg){
		try {
			// 通知合作机构赎回结果
			dealService.doSendLoanRedemption(dto);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("发送回购通知失败："+ExceptionUtils.getStackTraceAsString(e));
		}
		return dataMsg;
	}
	
}